package com.mvp.mvpdemo.base

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent
import com.mvp.mvpdemo.net.APIService
import com.mvp.mvpdemo.net.RetrofitClient
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import java.lang.ref.WeakReference


/**
 * Date    2020/10/15 17:44
 *         activity/fragment中创建对应presenter实例使用
 */
abstract class BasePresenter<M : IModel, V : IBaseView> : IPresenter<V> {
    /**
     * 创建协程
     */
    protected val coroutineScope= CoroutineScope(Dispatchers.Main)
    private var mView: WeakReference<V>? = null
    protected var mModel: M? = null
//model    protected val apiService: APIService by lazy { RetrofitClient.getInstance().getApi() }

    abstract fun createModel(): M

    /**
     * 绑定View
     * @param view
     */
    override fun attachView(view: V) {
        mView = WeakReference(view)
        mModel = createModel()
        mModel?.attach()
        if (view is LifecycleOwner) {
            (view as LifecycleOwner).lifecycle.addObserver(this)
            if (mModel != null && mModel is LifecycleObserver) {
                (view as LifecycleOwner).lifecycle.addObserver(mModel as LifecycleObserver)
            }
        }
    }

    /**
     * 获取绑定view
     * @return V?
     */
    override fun getView(): V? = mView?.get()

    /**
     * 解绑view
     * @param
     */
    override fun detachView() {
        if (mView != null) {
            mView?.clear()
            mView = null
        }
        mModel?.detach()
        coroutineScope.cancel()
    }


    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onDestroy() {
        detachView()
    }

    override fun showLoading() {
        getView()?.showLoading()
    }

    override fun hideLoading() {
        getView()?.hideLoading()
    }

}